package maquinavotar.view;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import maquinavotar.MaquinaVotarApp;
import maquinavotar.dto.CandidateDTO;
import maquinavotar.dto.ElectionDTO;
import maquinavotar.dto.PostDTO;
import maquinavotar.utils.HistoryManager;
import maquinavotar.utils.RandomizingTool;

public class SelectionVoteScreen extends JPanel {
    
    private boolean init = false;
    private ArrayList<JPanel> radioPanels = null;
    private HistoryManager history = null;
   
    private static SelectionVoteScreen INSTANCE = null;
    
    private SelectionVoteScreen() {}
            
    private synchronized static void createInstance(final MaquinaVotarApp app) {
    
        INSTANCE = new SelectionVoteScreen();
        INSTANCE.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Selección de voto"));
        INSTANCE.add(new JLabel("Error: no existen candidatos cargados."));
        
        JButton btn_next = new JButton("Retirar tarjeta");
        btn_next.addMouseListener(new java.awt.event.MouseAdapter() {
                @Override
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    app.showScreen(0,1);
                }
            });
        INSTANCE.add(btn_next);
        
    }
    
    public static SelectionVoteScreen getInstance(final MaquinaVotarApp app) {
        if (INSTANCE == null)
            createInstance(app);
        return INSTANCE;
    }
    
    public void init(final MaquinaVotarApp app) {
        
        if(app.cands != null) {

            this.removeAll();
            
            history = new HistoryManager();

            INSTANCE.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Selección de voto"));
            INSTANCE.setLayout(new BoxLayout(INSTANCE,BoxLayout.Y_AXIS));
            
            if(app.vote == null) {
                app.vote = new ArrayList<ElectionDTO>();
                app.cands = RandomizingTool.getArrayRandom(app.cands);
            }

            JPanel panelButton = new JPanel();
            panelButton.setLayout(new FlowLayout());
            
            JButton btn_next = new JButton("Confirmar", new ImageIcon("imgs/ok.png"));
            btn_next.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    saveVoto(app);
                    app.showScreen(2,1);
                }
            });
            panelButton.add(btn_next);

            JButton btn_undo = new JButton("Deshacer", new ImageIcon("imgs/undo.png"));
            btn_undo.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    if(history.existHistory()) {
                        radioPanels = history.loadHistory(SelectionVoteScreen.getInstance(app), radioPanels);
                        
                        for(int i=0; i<radioPanels.size(); i++) // Add panels RadioButton of layout
                            SelectionVoteScreen.getInstance(app).add(radioPanels.get(i));
                        
                        refresh();
                    } else {
                        init(app);
                        app.showScreen(1, 1);
                    }
                }
            });
            panelButton.add(btn_undo);
            
            
            JButton btn_reset = new JButton("Resetear", new ImageIcon("imgs/reset.png"));
            btn_reset.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    init(app);
                    app.showScreen(1, 1);
                }
            });
            panelButton.add(btn_reset);
            
            this.add(panelButton);
            showCandidates(app);

            init = true;
        
        }
    }

    public boolean isInitialization() {
        return init;
    }
    
    private void showCandidates(final MaquinaVotarApp app) {
        
        radioPanels = new ArrayList<JPanel>();
        
        for(String post : PostDTO.getAllPost()) {
            final ButtonGroup bgroup = new ButtonGroup();
            JPanel radioPanel = new JPanel();
            radioPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), post));
            radioPanel.setName(post);
            
            for(CandidateDTO c : app.cands) {
                if(c.puesto.equals(post)) {
                    
                    JRadioButton radioButton = new JRadioButton(c.nombre,/* new ImageIcon("imgs/cands/user.png"),*/ false);
                    bgroup.add(radioButton);
                    radioPanel.add(radioButton);
                    radioButton.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(ActionEvent ae) {
                            history.updateHistory(radioPanels);                            
                        }
                    });
                    
                }
            }

            this.add(radioPanel);
            radioPanels.add(radioPanel);
        }
        
    }
    
    private void saveVoto(final MaquinaVotarApp app) {
        app.vote = new ArrayList<ElectionDTO>();
        for(int i=0; i<radioPanels.size(); i++) {
            JPanel radioPanel = radioPanels.get(i);
            for (int j = 0; j < radioPanel.getComponentCount(); j++) {
                JRadioButton radioButton = (JRadioButton) radioPanel.getComponents()[j];
                if(radioButton.isSelected()) {
                    app.vote.add(new ElectionDTO(radioButton.getText(), radioPanel.getName()));
                    break;
                }
            }
        }
    }
    
    public void refresh() {
        this.setVisible(false);
        this.setVisible(true);
    }
    
}